<template>
  <div class="class-times-container">
    <el-dropdown placement="left-start" @command="handle">
      <div :class="['times-item', { 'active': data.isShowDetail }]">
        <div class="item-header" @click="data.isShowDetail = !data.isShowDetail">
          <i :class="[`el-icon-caret-${data.isShowDetail ? 'bottom' : 'right'}`]" />
          <h4>第{{ chinesNumber }}讲</h4>
          <h4>{{ data.indexName }}</h4>
          <span>
            （
            <i>{{ data.period }}</i>课时）
          </span>
          <div class="icon" @click.stop="edit" v-if="isEdit">
            <i class="el-icon-edit-outline" />
          </div>
          <div class="icon" @click.stop="remove" v-if="isEdit && data.isRemove">
            <i class="el-icon-delete" />
          </div>
          <div class="actions">
            <div @click.stop class="click-stop" v-if="isEdit">
              <el-dropdown trigger="click" @command="addEntranceExam" v-if="!data.exam">
                <el-button size="mini">添加进门考</el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="0">新建进门考</el-dropdown-item>
                    <el-dropdown-item :command="1">选择进门考</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <el-dropdown trigger="click" @command="editEntranceExam" v-else>
                <el-button size="mini" type="warning">编辑进门考</el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="{type: 0, data: data}">取消，重新添加</el-dropdown-item>
                    <el-dropdown-item :command="{type: 1, data: data}" v-if="!data.exam.filePath">编辑进门考</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <el-dropdown trigger="click" @command="addHandout" v-if="!data.child">
                <el-button size="mini">添加讲义</el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="0">新建讲义</el-dropdown-item>
                    <el-dropdown-item :command="1">选择标准讲义</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <el-dropdown trigger="click" @command="editHandout" v-else >
                <el-button size="mini" type="warning">编辑讲义</el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="{type: 0, data: data}" >取消，重新添加</el-dropdown-item>
                    <el-dropdown-item :command="{type: 1, data: data}" v-if="!data.child.path">编辑讲义</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <el-dropdown trigger="click" @command="addHomework" v-if="!data.homework">
                <el-button size="mini">添加巩固练习</el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="0">新建巩固练习</el-dropdown-item>
                    <el-dropdown-item :command="1">选择巩固练习</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <el-dropdown trigger="click" @command="editHomework" v-else>
                <el-button size="mini" type="warning">编辑巩固练习</el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="{type: 0, data: data}">取消，重新添加</el-dropdown-item>
                    <el-dropdown-item :command="{type: 1, data: data}" v-if="!data.homework.filePath">编辑巩固练习</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
          <!-- <div class="actions">
            <template v-if="data.child && data.child.handoutId && isEdit">
              <el-button size="mini" type="warning" @click.stop="removeHandout(data)">取消添加讲义</el-button>
              <el-button
                size="mini"
                v-if="data.child.type === 3 || data.child.type === 2"
                :type="data.isShowDetail ? 'primary' : null"
                @click.stop="editHandout(data.child.handoutId)"
              >编辑讲义</el-button>
            </template>
            <template v-else-if="isEdit && (!data.child || !data.child.handoutId)">
              <el-button
                size="mini"
                :type="data.isShowDetail ? 'primary' : null"
                @click.stop="addHandout"
              >添加标准讲义</el-button>
              <el-button
                size="mini"
                :type="data.isShowDetail ? 'primary' : null"
                @click.stop="createHandout"
              >新建讲义</el-button>
            </template>
          </div> -->
        </div>
           <el-collapse-transition>
          <div class="item-content" v-show="data.isShowDetail">
            <div v-if="data.exam || data.child || data.homework">
              <div class="item-exam" v-if="data.exam">
                <p><span class="tip">进门考</span>  {{ data.exam.title }}</p>
              </div>
              <div class="item-child" v-if="data.child">
                <p><span class="tip">讲义</span> {{ data.child.name }}</p>
              </div>
              <div class="item-homework" v-if="data.homework">
                <p><span class="tip">课堂巩固</span> {{ data.homework.title }}</p>
              </div>
            </div>
            <cus-empty v-else />
            <div class="item-footer"><div>{{ data.difficultPoint || '暂无重难点描述' }}</div></div>
          </div>
        </el-collapse-transition>
      </div>
      <template #dropdown v-if="isEdit">
        <h2 style="text-indent: 16px; margin-top: 12px">添加课次:</h2>
        <el-dropdown-menu>
          <el-dropdown-item :command="0">从其他计划选择</el-dropdown-item>
          <el-dropdown-item :command="1">批量添加</el-dropdown-item>
          <el-dropdown-item :command="2">空白课次</el-dropdown-item>
          <el-dropdown-item :command="3">阶段测试</el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script lang="ts">
import $ from '$'
import { ElMessageBox } from 'element-plus'
import AddHandoutComponent from '@/views/teaching-plan/update/components/add-handout.vue'
import AddTestPaperComponent from '@/views/teaching-plan/update/components/add-test-paper.vue';
import NewExerciseComponent from '@/views/sync-practice/components/new-exercise.vue'
import { computed, onUnmounted, ref } from 'vue'
import PlanListComponent from '@/views/one-prepare/prepare-edit/components/chioce-other-plan.vue'
export default {
  props: {
    data: {
      type: Object,
      required: true,
    },
    index: {
      type: Number,
      required: true,
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
    oldData: {
      type: Object,
      required: true,
    },
    subjectId: {
      type: String,
      default: '',
    },
    lessonType:{
      type: Number,
    }
  },
  setup(props, { emit }) {
    const { lessonId, lessonThirdId, planId } = props.oldData
    let lessonData = ref({
      indexName: '',
      period: null,
      lessonId,
      lessonThirdId,
      difficultPoint: '',
      sortNum: null,
      status: 0,
      checked: 0,
      planId,
      id: null,
      handoutId: null,
      child: { handoutId: null },
    })
    let curHandoutId = ref('')
    let knowledgeList = computed(() =>
      props.data?.child?.type !== 1 ? props.data.child?.childs : null
    )
    const chinesNumber = computed(() => {
      return $.math.toChines(props.index + 1)
    })

    const handle = (type) => {
      type === 0
        ? __otherAddition(props.index + 1)
        : __manualAddition(type, props.index + 1)
    }

    const __manualAddition = async (type, sortNum) => {
      let nodes: any[] =
        type === 1
          ? [
              {
                label: '次数',
                type: 'number',
                key: 'sumTimes',
                min: 1,
                step: 1,
                strictly: true,
                rule: [{ required: true, message: '请输入次数' }],
              },
              {
                label: '课时',
                type: 'number',
                key: 'period',
                min: 1,
                step: 1,
                strictly: true,
                rule: [{ required: true, message: '请输入课时数' }],
                default: 2,
              },
            ]
          : [
              {
                label: '名称',
                default: type === 2 ? null : '阶段测试',
                type: 'input',
                key: 'indexName',
                min: 1,
                step: 1,
                strictly: true,
                rule: [{ required: true, message: '请输入名称' }],
              },
              {
                label: '课时',
                type: 'number',
                key: 'period',
                min: 1,
                step: 1,
                strictly: true,
                rule: [{ required: true, message: '请输入课时数' }],
              },
              { label: '重难点', type: 'textarea', key: 'difficultPoint' },
            ]
      let title = `${type === 1 ? '批量' : ''}添加课次`
      let formGroup = await $.modal.create({
        title,
        width: 400,
        zIndex: 2015,
        props: { nodes },
      })
      formGroup.isRemove = true
      if (type === 1) {
        for (let i = 0; i < formGroup.sumTimes; i++) {
          emit(
            'edit-lesson',
            {
              indexName: `第${sortNum + i + 1}讲`,
              period: formGroup.period,
              lessonId,
              lessonThirdId,
              difficultPoint: '',
              sortNum: sortNum + i + 1,
              status: 0,
              checked: 0,
              planId,
              id: null,
              handoutId: null,
              child: { handoutId: null },
              isRemove: true,
            },
            sortNum + i + 1,
            true
          )
        }
      } else {
        emit(
          'edit-lesson',
          Object.assign(lessonData.value, formGroup, { sortNum: sortNum + 1 }),
          sortNum,
          true
        )
      }
    }
    const __otherAddition = async (sortNum) => {
      let ids = await $.modal.create({
        title: '选择其他学生教学计划',
        width: 505,
        zIndex: 2015,
        bodyStyle: { padding: '0' },
        component: PlanListComponent,
      })
      if (ids[0].length > 0) {
        ids[0].forEach((ele, index) => {
          ele.isRemove = true
          ele.lessonId = props.lessonType
            ? props.data.lessonId
            : props.data.contractId
          ele.lessonThirdId = null
          ele.id = null
          ele.sortNum = sortNum + index + 1
          ele.status = 0
          emit('edit-lesson', ele, sortNum + index + 1, true)
        })
      }
    }
    const edit = async () => {
      let formGroup = await $.modal.create({
        title: '修改课次',
        width: 400,
        zIndex: 2015,
        props: {
          nodes: [
            {
              label: '名称',
              default: props.data.indexName,
              type: 'input',
              key: 'indexName',
              rule: [{ required: true, message: '请输入名称' }],
            },
            {
              label: '课时',
              default: props.data.period,
              type: 'number',
              key: 'period',
              min: 1,
              step: 1,
              strictly: true,
              rule: [{ required: true, message: '请输入课时数' }],
            },
            {
              label: '重难点',
              default: props.data.difficultPoint,
              type: 'textarea',
              key: 'difficultPoint',
            },
          ],
        },
      })
      let data = Object.assign(
        props.data.id ? props.data : lessonData.value,
        formGroup
      )
      emit('edit-lesson', data, props.index)
    }

    const remove = async () => {
      emit('remove-lesson', props.index)
    }

    const removeHandout = async (data) => {
      await ElMessageBox.confirm('确认解绑标准讲义吗？', {
        type: 'warning',
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      })
      data.handoutId = null
      data.child = { handoutId: null }
      emit('edit-lesson', data, props.index)
    }

    const addHandout = async (command) => {
      if (command) {
        let title = '添加标准讲义'
        let result = await $.drawer.create({
          title,
          width: 1080,
          zIndex: 2016,
          component: AddHandoutComponent,
        })
        curHandoutId.value = result.id
        handoutChange()
      } else {
        let handout = await $.http.json('/admin/material/saveMaterial', {
          type: 3,
          fileName: props.data.indexName,
          isPublic: 0,
        })
        let res = await $.http.post(
          '/admin/teachTimesHandoutRelation/saveOrUpdate',
          { indexId: props.data.id, type: 3, handoutId: handout.json.id }
        )
        curHandoutId.value = handout.json.id
        handoutChange()
        res.result && window.open(`/#/handout/false/${handout.json.id}/${props.subjectId}`)
      }
    }
    const addEntranceExam = async (command) => {
       if (!command) {
        $.modal.create({title: '新建进门考', width: 640, component: NewExerciseComponent, props: { paperType: 1, plan: true, addPaper: (data) => __courseAddData(data, '新建进门考', 'exam', command) }, zIndex: 2016})
      } else {
        let title = '选择进门考试卷';
        $.drawer.create({ title, width: 1080, zIndex: 2016, component: AddTestPaperComponent, props: { subjectCode: props.subjectId, addData: (data) => __courseAddData(data, title, 'exam', command), } })
      }
    }
    const addHomework = async (command) => {
      if (!command) {
        $.modal.create({title: '新建练习', width: 640, component: NewExerciseComponent, props: { paperType: 1, plan: true, addPaper: (data) => __courseAddData(data, '新建练习', 'homework', command) }, zIndex: 2016})
      } else {
        let title = '选择练习试卷';
        $.drawer.create({ title, width: 1080, zIndex: 2016, component: AddTestPaperComponent, props: { subjectCode: props.subjectId, addData: (data) => __courseAddData(data, title, 'homework', command), } });
      }
    }

    // data试卷数据 title弹窗标题 type试卷类型 command新建或者选择
    const __courseAddData = async (data, title, type, command) => {
      let exam, homework, examId: string = '', homeworkId: string = ''
      if (type === 'exam') {
        examId = data.id
        homeworkId = props.data.homework ? props.data.homework.id : null
        exam = data
        homework = props.data.homework
      } else {
        examId = props.data.exam ? props.data.exam.id : null
        homeworkId = data.id
        exam = props.data.exam
        homework = data
      }
      emit(
        'edit-lesson',
        Object.assign(props.data, { exam, homework, examId, homeworkId }),
        props.index
      )
      $.utils.message(true, title);
      $.emitter.emit('class-times-change');
      if (!command) window.open(`./#/test-paper-edit/${false}/${data.id}/${true}`);
    }

    const handoutChange = async () => {
      if (!curHandoutId.value) return
      let result: any = await $.http.post('/admin/material/queryById', {
        id: curHandoutId.value,
      })
      let resList = await $.http.post('/admin/handoutNode/query', {
        handoutId: result.json.id,
      })
      let child = {
        name: result.json.fileName,
        handoutId: result.json.id,
        childs: resList.json.filter((e) => {
          e.child = null
          e.name = e.content
          return e.type === 3
        }),
        type: result.json.type,
      }
      emit(
        'edit-lesson',
        Object.assign(props.data, {
          handoutId: result.json.id,
          child,
          handoutType: result.json.type,
        }),
        props.index
      )
    }
    const __postMessageFn = ({ origin, data }) => {
      origin === window.location.origin &&
      data.type === 'handout-save-success' &&
      handoutChange()
    }
    window.addEventListener('message', __postMessageFn)
    onUnmounted(() => window.removeEventListener('message', __postMessageFn))

    const editHandout = async (command) => {
      if (!command.type) {
        await ElMessageBox.confirm('确认解绑标准讲义吗？', {
        type: 'warning',
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      })
      command.data.handoutId = null
      command.data.child = null
      emit('edit-lesson', command.data, props.index)
      } else {
        window.open(`/#/handout/false/${command.data.child.handoutId}/${props.subjectId}`)
      }
    }
    const editEntranceExam = async (command) => {
      if (!command.type) {
        await ElMessageBox.confirm('确认解绑标准试卷吗？', { type: 'warning', confirmButtonText: '确认', cancelButtonText: '取消' });
        command.data.homeworkId = command.data.homework ? command.data.homework.id : null
        command.data.examId = null
        command.data.exam = null
        emit('edit-lesson', command.data, props.index)
        $.utils.message(true, '解绑标准试卷');
        $.emitter.emit('class-times-change');
      } else {
         window.open(`./#/test-paper-edit/${false}/${command.data.exam.id}/${true}`);
      }
    }
    const editHomework = async (command) => {
      if (!command.type) {
        await ElMessageBox.confirm('确认解绑标准试卷吗？', { type: 'warning', confirmButtonText: '确认', cancelButtonText: '取消' });
        command.data.examId = command.data.exam ? command.data.exam.id : null
        command.data.homeworkId = null
        command.data.homework = null
        $.utils.message(true, '解绑标准试卷');
        $.emitter.emit('class-times-change');
      } else {
         window.open(`./#/test-paper-edit/${false}/${command.data.homework.id}/${true}`);
      }
    }

    return {
      handle,
      chinesNumber,
      edit,
      addHandout,
      removeHandout,
      knowledgeList,
      editHandout,
      remove,
      handoutChange,
      curHandoutId,
      addEntranceExam,
      addHomework,
      editEntranceExam,
      editHomework
    }
  },
}
</script>

<style lang="scss" scoped>
.class-times-container {
  & > div:not(:last-child) {
    margin-bottom: 20px;
  }
  :deep(.el-dropdown) {
    display: block;
  }
  .times-item {
    outline: none;
    &.active {
      .item-header {
        background: #fff;
        border-left-color: #72b22a;
        box-shadow: 0px 1px 8px 0px rgba(72, 72, 72, 0.2);
      }
    }
    .item-header {
      display: flex;
      padding: 13px 20px;
      line-height: 28px;
      background: #eff2f5;
      border-left: solid 5px #eff2f5;
      border-radius: 4px;
      transition: all 0.2s;
      cursor: pointer;
      & > i {
        font-size: 20px;
        line-height: 28px;
        margin-right: 10px;
      }
      & > h4 {
        margin-right: 20px;
        font-size: 16px;
      }
      & > span {
        color: #999;
        i {
          color: #faad14;
          margin: 0 2px;
        }
      }
      .icon {
        width: 26px;
        height: 26px;
        margin-right: 10px;
        color: #3d3078;
        font-size: 16px;
        line-height: 26px;
        text-align: center;
        background: #f5f7fa;
        border-radius: 4px;
        transition: all 0.2s;
        &:active,
        &:hover {
          background: #ddd;
        }
        &:active {
          transform: scale(0.9);
        }
        &.loading {
          pointer-events: none;
        }
      }
      .actions {
        margin-left: auto;
        .click-stop {
          display: flex;
        }
      }
      .el-button {
        border-radius: 14px;
        margin-left: 8px;
      }
    }
    .item-content {
      border-radius: 6px;
      border: solid 1px #72b22a;
      border-top-color: transparent;
      overflow: hidden;
    }
    .item-child, .item-exam, .item-homework {
      padding: 10px 50px;
      .tip {
        color: $--color-remind;
      }
      .type-file {
        display: flex;
        & > p {
          margin-left: 20px;
          color: #333;
          font-size: 16px;
          line-height: 40px;
        }
      }
      .type-other {
        .item-title {
          display: flex;
          line-height: 20px;
          cursor: pointer;
          i {
            color: #999;
            font-size: 16px;
            line-height: inherit;
          }
          h4 {
            margin: 0 20px 0 10px;
          }
        }
        .item-main {
          margin-top: 17px;
          & > div {
            display: flex;
            padding-left: 43px;
            line-height: 54px;
            &:hover {
              background: #F5F7FA;
            }
            img {
              display: block;
              margin-right: 20px;
              height: 14px;
              margin-top: 20px;
            }
          }
        }
      }
    }
    .item-footer {
      display: flex;
      height: 52px;
      background: rgba(#faad14, 0.1);
      position: relative;
      overflow: hidden;
      &::before {
        content: '重难点';
        display: block;
        width: 70px;
        height: 100%;
        padding-left: 20px;
        color: #9f6e0c;
        line-height: 52px;
        font-size: 16px;
        background: #fcdb9b;
        box-sizing: border-box;
      }
      &::after {
        content: '';
        display: inline-block;
        width: 0;
        height: 4px;
        border: solid 30px transparent;
        border-left-color: #fcdb9b;
        transform: scaleX(0.7);
        position: absolute;
        bottom: 0;
        left: 60px;
        margin-bottom: -6px;
      }
      & > div {
        flex: 1 1 70px;
        padding: 0 20px 0 40px;
        font-size: 16px;
        line-height: 52px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
  }
}
</style>
